from flask import render_template, redirect, url_for, abort, flash, request, jsonify
from flask_login import login_required, current_user
from . import main
from .forms import EditProfileForm, EditProfileAdminForm
from .. import db
from ..models import Role, User, Balance, orderResponse, Trade, marketData, BalanceEstimate
from ..decorators import admin_required, view_required
import json
from random import random
from datetime import datetime
from time import gmtime
import time, logging
from sqlalchemy import extract, cast, DATE


@main.route('/')
def index():
    return render_template('index.html')


@main.route('/user/<username>')
def user(username):
    user = User.query.filter_by(username=username).first_or_404()
    return render_template('user.html', user=user)


@main.route('/edit-profile', methods=['GET', 'POST'])
@login_required
def edit_profile():
    form = EditProfileForm()
    if form.validate_on_submit():
        current_user.name = form.name.data
        current_user.location = form.location.data
        current_user.about_me = form.about_me.data
        db.session.add(current_user)
        flash('Your profile has been updated.')
        return redirect(url_for('.user', username=current_user.username))
    form.name.data = current_user.name
    form.location.data = current_user.location
    form.about_me.data = current_user.about_me
    return render_template('edit_profile.html', form=form)


@main.route('/edit-profile/<int:id>', methods=['GET', 'POST'])
@login_required
@admin_required
def edit_profile_admin(id):
    user = User.query.get_or_404(id)
    form = EditProfileAdminForm(user=user)
    if form.validate_on_submit():
        user.email = form.email.data
        user.username = form.username.data
        user.confirmed = form.confirmed.data
        user.role = Role.query.get(form.role.data)
        user.name = form.name.data
        user.location = form.location.data
        user.about_me = form.about_me.data
        db.session.add(user)
        flash('The profile has been updated.')
        return redirect(url_for('.user', username=user.username))
    form.email.data = user.email
    form.username.data = user.username
    form.confirmed.data = user.confirmed
    form.role.data = user.role_id
    form.name.data = user.name
    form.location.data = user.location
    form.about_me.data = user.about_me
    return render_template('edit_profile.html', form=form, user=user)


data_info = []


@main.route('/update_balance_estimate', methods=['POST'])
def update_balance_estimate():
    try:
        if request.method == 'POST':
                for data in json.loads(request.data):
                    # print(data)
                    balance_estimate = BalanceEstimate(platform=data.get('platform', None),
                                                       logtime=datetime.fromtimestamp(data.get('logtime', 0)),
                                                       ETH=data.get('ETH', None),
                                                       BTC=data.get('BTC', None),
                                                       EOS=data.get('EOS', None),
                                                       XRP=data.get('XRP', None),
                                                       BCH=data.get('BCH', None),
                                                       DASH=data.get('DASH', None),
                                                       ZEC=data.get('ZEC', None),
                                                       NEO=data.get('NEO', None),
                                                       VEN=data.get('VEN', None),
                                                       BNB=data.get('BNB', None),
                                                       USDT=data.get('USDT', None),
                                                       USD=data.get('USD', None),
                                                       CNY=data.get('CNY', None),
                                                       Total_BTC=data.get('Total(BTC)', None),
                                                       Total_USD=data.get('Total(USD)', None),
                                                       Value_BTC=data.get('Value(BTC)', None),
                                                       Value_USD=data.get('Value(USD)', None)
                                                       )
                    db.session.add(balance_estimate)
                    db.session.commit()
    except Exception as e:
        pass
    return jsonify()


@main.route('/update_balance', methods=['POST'])
def update_balance():
    try:
        if request.method == 'POST':
                logging.info(json.loads(request.data))
                for data in json.loads(request.data):
                    # print(data)
                    balance = Balance(platform=data.get('platform', None),
                                      logtime=datetime.fromtimestamp(data.get('logtime', 0)),
                                      ETH=data.get('ETH', None),
                                      BTC=data.get('BTC', None),
                                      EOS=data.get('EOS', None),
                                      XRP=data.get('XRP', None),
                                      BCH=data.get('BCH', None),
                                      DASH=data.get('DASH', None),
                                      ZEC=data.get('ZEC', None),
                                      NEO=data.get('NEO', None),
                                      VEN=data.get('VEN', None),
                                      BNB=data.get('BNB', None),
                                      USDT=data.get('USDT', None),
                                      USD=data.get('USD', None),
                                      CNY=data.get('CNY', None),
                                      Total_BTC=data.get('Total(BTC)', None),
                                      Total_USD=data.get('Total(USD)', None),
                                      Value_BTC=data.get('Value(BTC)', None),
                                      Value_USD=data.get('Value(USD)', None)
                                      )
                    db.session.add(balance)
                    db.session.commit()
    except Exception as e:
        logging.info(e)
    return jsonify()


@main.route('/balance', methods=['GET'])
@login_required
@view_required
def balance():
    if request.method == 'GET':
        return render_template('balance.html')


def query_total_balance(cmd=None):
    try:
        all_balance = []
        all_balance_list = []
        if cmd is None:
            all_balance = Balance.query.filter_by().all()
            for balance in all_balance:
                temp = balance.parse_data_to_bootstrap_table()
                all_balance_list.append(temp)
        elif cmd == 'last':
            balance = Balance.query.filter_by(platform='summary').order_by(Balance.logtime.desc()).first()
            percentage = Balance.query.filter_by(platform='percentage').order_by(Balance.logtime.desc()).first()
            temp = balance.parse_data_to_bootstrap_table()
            temp1 = percentage.parse_data_to_bootstrap_table()
            for key, value in temp.items():
                if key is not 'Platform':
                    if key is 'Total_USD':
                        try:
                            value = str(round(float(value), 2))
                        except Exception as e:
                            value = u'None'
                        all_balance_list.append({'Coin': key + u' (仅供参考)', 'Quantity': value, 'Percent': temp1[key]})
                    elif key is 'logtime':
                        all_balance_list.append({'Coin': 'Time', 'Quantity': value.strftime('%Y-%m-%d %H:%M:%S')})
                    else:
                        value1 = None
                        try:
                            value = str(round(float(value), 2))
                            if current_user.role_id == 3:
                                value1 = str(round(float(temp1[key]) * 100, 4)) + '%'
                        except Exception as e:
                            pass
                            # print(e)
                        all_balance_list.append({'Coin': key, 'Quantity': value, 'Percent': value1})
        elif cmd == 'all':
            NOW = datetime.now()
            all_balance = Balance.query.filter(cast(Balance.logtime, DATE) < NOW.date(),
                                               extract('minute', Balance.logtime) >= 0,
                                               extract('minute', Balance.logtime) < 5,
                                               Balance.platform == "summary"
                                               ).order_by(Balance.logtime.asc()).all()
            for balance in all_balance:
                all_balance_list.append([balance.logtime.strftime('%Y-%m-%d %H:%M:%S'),
                                         float(balance.Value_BTC), float(balance.Value_USD)])
    except Exception as e:
        pass
        # print(e)
    return all_balance_list


@main.route('/balance_info', methods=['GET'])
@login_required
@view_required
def balance_info():
    if request.method == 'GET':
        balance_info_list = query_total_balance()
    return jsonify(balance_info_list)


@main.route('/balance_last_info', methods=['GET'])
@login_required
@view_required
def balance_last_info():
    if request.method == 'GET':
        balance_info_list = query_total_balance('last')
    return jsonify(balance_info_list)


@main.route('/balance_summary_info', methods=['GET'])
@login_required
@view_required
def balance_summary_info():
    if request.method == 'GET':
        balance_info_list = query_total_balance('all')
    return jsonify(balance_info_list)


@main.route('/order_response', methods=['Post'])
def order_response():
    try:
        if request.method == 'POST':
            for data in json.loads(request.data):
                # print(data)
                response = orderResponse(logtime=datetime.fromtimestamp(data.get('logtime', 0)),
                                         response=data.get('response', None)
                                         )
                db.session.add(response)
                db.session.commit()
    except Exception as e:
        pass
    return jsonify()


@main.route('/trade', methods=['Post'])
def trade():
    try:
        if request.method == 'POST':
            for data in json.loads(request.data):
                # print(data)
                trade = Trade(platform=data.get('platform', None),
                              logtime=datetime.fromtimestamp(data.get('logtime', 0)),
                              commodity_cur=data.get('commodity_cur', None),
                              base_cur=data.get('base_cur', None),
                              type=data.get('type', None),
                              order=data.get('order', None),
                              quantity=data.get('quantity', None),
                              price=data.get('price', None)
                              )
                db.session.add(trade)
                db.session.commit()
    except Exception as e:
        pass
    return jsonify()


@main.route('/market_data', methods=['Post'])
def market_data():
    try:
        if request.method == 'POST':
            for data in json.loads(request.data):
                # print(data)
                market_data = marketData(platform=data.get('platform', None),
                                         logtime=datetime.fromtimestamp(data.get('logtime', 0)),
                                         price_bid=data.get('price_bid', None),
                                         price_ask=data.get('price_ask', None),
                                         volume_bid=data.get('volume_bid', None),
                                         volume_ask=data.get('volume_ask', None)
                                         )
                db.session.add(market_data)
                db.session.commit()
    except Exception as e:
        pass
    return jsonify()
